<?php

namespace App\Http\Controllers\Api\v2;

use App\Http\Controllers\ApiController;
use App\Models\DeviceToken;
use App\Models\JPush;

class ApnsController extends ApiController
{
    public function deviceToken()
    {
        $device_token = $this->request->input('device_token');

        if (!$device_token) return ajaxReturn();
        if (DeviceToken::where('device_token', $device_token)->exists()){
            DeviceToken::where('device_token', $device_token)->update(['uid'=>$this->uid]);
        } else {
            if ($this->uid) {
                if (DeviceToken::where('uid', $this->uid)->exists()){
                    DeviceToken::where('uid', $this->uid)->update(['device_token'=>$device_token]);
                } else {
                    DeviceToken::insert([
                        'uid'=>$this->uid,
                        'device_token'=>$device_token
                    ]);
                }
            } else {
                DeviceToken::insert([
                    'device_token'=>$device_token
                ]);
            }
        }

        return ajaxReturn();
    }

    public function jpush(){

        if ($this->uid) {
            $platform = $this->request->input('platform');
            $registrationid = $this->request->input('registrationid');

            if (JPush::where('uid', $this->uid)->exists()) {
                if ($platform === 'ios') {
                    JPush::where('uid',$this->uid)->update(['ios'=>$registrationid]);
                } else {
                    JPush::where('uid',$this->uid)->update(['android'=>$registrationid]);
                }
            } else {
                if ($platform === 'ios') {
                    JPush::insert([
                        'uid'=>$this->uid,
                        'ios'=>$registrationid
                    ]);
                } else {
                    JPush::insert([
                        'uid'=>$this->uid,
                        'android'=>$registrationid
                    ]);
                }
            }
        }

        return ajaxReturn();
    }
}
